package com.ljx.hzit.controller.admin;

import com.ljx.hzit.entity.LoginUser;
import com.ljx.hzit.entity.User;
import com.ljx.hzit.service.TokenService;
import com.ljx.hzit.service.UserService;
import com.ljx.hzit.utils.JwtUtil;
import com.ljx.hzit.utils.R;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/user")
@Api(tags = "用户登录、注册接口")
public class AdminLoginController {
	@Autowired
	private UserService userService;
	@Autowired
	private TokenService tokenService;
	//1. 用户登录
	@PostMapping("/login")
	@ApiOperation("登录")
	public R login(
			@ApiParam(value="登录用户对象",required = true)
			@RequestBody User user) {
		// 1.1 根据用户名或密码查询用户
		LoginUser loginUser = userService.findById(user.getUsername(),user.getPassword());
		Map<String,Object> map = tokenService.createToken(loginUser);
		return R.ok().data(map);
	}

	@GetMapping("/info")
	public R info(@RequestParam("token") String token){
		Claims claims = JwtUtil.parseToken(token);
		String username = (String) claims.get("username");

		Map map = new HashMap();
		map.put("name",username);
		map.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
		R data = R.ok().data(map);
		return data;
	}
	@PostMapping("/signIn")
	public R userSignIn(@RequestBody User user){
		boolean i = userService.saveUserMsg(user);
		return i?R.ok().code(200).message("注册成功"):R.error();
	}
}
